import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { CleanupTask, CleanupTaskQuery, CleanupTaskForm, CleanupTaskStats, CleanupStaff } from '@/types/cleanup'
import { CleanupStatus, OverflowStatus } from '@/types/cleanup'

// 分页信息接口
interface Pagination {
  current: number
  size: number
  total: number
}

// 模拟清运任务数据
const mockCleanupTasks: CleanupTask[] = [
  {
    id: 1,
    taskCode: 'CLEAN-20240115-001',
    deviceCode: 'DLF-001',
    deviceLocation: '北京市朝阳区建国路88号',
    area: '朝阳区',
    wasteType: 'paper',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 95,
    maxCapacity: 100,
    cleanupStaffId: 101,
    cleanupStaffName: '张三',
    cleanupStaffPhone: '13800138101',
    status: CleanupStatus.Pending,
    notes: '设备已满溢，需要尽快清运',
    createdAt: '2024-01-15 08:30:00',
    updatedAt: '2024-01-15 08:30:00'
  },
  {
    id: 2,
    taskCode: 'CLEAN-20240115-002',
    deviceCode: 'DLF-002',
    deviceLocation: '上海市浦东新区陆家嘴环路1000号',
    area: '浦东新区',
    wasteType: 'textile',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 88,
    maxCapacity: 100,
    cleanupStaffId: 102,
    cleanupStaffName: '李四',
    cleanupStaffPhone: '13800138102',
    status: CleanupStatus.Completed,
    notes: '清运任务已完成',
    createdAt: '2024-01-15 08:45:00',
    updatedAt: '2024-01-15 09:30:00'
  },
  {
    id: 3,
    taskCode: 'CLEAN-20240115-003',
    deviceCode: 'DLF-003',
    deviceLocation: '广州市天河区体育西路189号',
    area: '天河区',
    wasteType: 'mixed',
    overflowStatus: OverflowStatus.NEAR_FULL,
    currentWeight: 85,
    maxCapacity: 100,
    cleanupStaffId: 103,
    cleanupStaffName: '王五',
    cleanupStaffPhone: '13800138103',
    status: CleanupStatus.PENDING,
    notes: '接近满溢状态，建议安排清运',
    createdAt: '2024-01-15 09:30:00',
    updatedAt: '2024-01-15 09:30:00'
  },
  {
    id: 4,
    taskCode: 'CLEAN-20240115-004',
    deviceCode: 'DLF-004',
    deviceLocation: '深圳市南山区科技园南区',
    area: '南山区',
    wasteType: 'paper',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 92,
    maxCapacity: 100,
    cleanupStaffId: 101,
    cleanupStaffName: '张三',
    cleanupStaffPhone: '13800138101',
    status: CleanupStatus.COMPLETED,
    notes: '清运任务已完成',
    createdAt: '2024-01-15 10:30:00',
    updatedAt: '2024-01-15 14:30:00'
  },
  {
    id: 5,
    taskCode: 'CLEAN-20240115-005',
    deviceCode: 'DLF-005',
    deviceLocation: '杭州市西湖区文三路398号',
    area: '西湖区',
    wasteType: 'textile',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 96,
    maxCapacity: 100,
    cleanupStaffId: 104,
    cleanupStaffName: '赵六',
    cleanupStaffPhone: '13800138104',
    status: CleanupStatus.PENDING,
    notes: '设备满溢严重，急需清运',
    createdAt: '2024-01-15 12:30:00',
    updatedAt: '2024-01-15 12:30:00'
  },
  {
    id: 6,
    taskCode: 'CLEAN-20240115-006',
    deviceCode: 'DLF-006',
    deviceLocation: '南京市鼓楼区中山北路32号',
    area: '鼓楼区',
    wasteType: 'mixed',
    overflowStatus: OverflowStatus.NEAR_FULL,
    currentWeight: 82,
    maxCapacity: 100,
    cleanupStaffId: 102,
    cleanupStaffName: '李四',
    cleanupStaffPhone: '13800138102',
    status: CleanupStatus.COMPLETED,
    notes: '清运任务已完成',
    createdAt: '2024-01-15 13:30:00',
    updatedAt: '2024-01-15 14:15:00'
  },
  {
    id: 7,
    taskCode: 'CLEAN-20240115-007',
    deviceCode: 'DLF-007',
    deviceLocation: '成都市武侯区人民南路四段',
    area: '武侯区',
    wasteType: 'paper',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 94,
    maxCapacity: 100,
    cleanupStaffId: 105,
    cleanupStaffName: '孙七',
    cleanupStaffPhone: '13800138105',
    status: CleanupStatus.PENDING,
    notes: '设备已满溢，等待清运',
    createdAt: '2024-01-15 14:30:00',
    updatedAt: '2024-01-15 14:30:00'
  },
  {
    id: 8,
    taskCode: 'CLEAN-20240115-008',
    deviceCode: 'DLF-008',
    deviceLocation: '武汉市江汉区解放大道',
    area: '江汉区',
    wasteType: 'textile',
    overflowStatus: OverflowStatus.NEAR_FULL,
    currentWeight: 78,
    maxCapacity: 100,
    cleanupStaffId: 103,
    cleanupStaffName: '王五',
    cleanupStaffPhone: '13800138103',
    status: CleanupStatus.PENDING,
    notes: '接近满溢状态，建议安排清运',
    createdAt: '2024-01-15 15:30:00',
    updatedAt: '2024-01-15 15:30:00'
  },
  {
    id: 9,
    taskCode: 'CLEAN-20240115-009',
    deviceCode: 'DLF-009',
    deviceLocation: '西安市雁塔区小寨西路',
    area: '雁塔区',
    wasteType: 'mixed',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 91,
    maxCapacity: 100,
    cleanupStaffId: 101,
    cleanupStaffName: '张三',
    cleanupStaffPhone: '13800138101',
    status: CleanupStatus.PENDING,
    notes: '设备满溢，需要清运',
    createdAt: '2024-01-15 16:30:00',
    updatedAt: '2024-01-15 16:30:00'
  },
  {
    id: 10,
    taskCode: 'CLEAN-20240115-010',
    deviceCode: 'DLF-010',
    deviceLocation: '重庆市渝中区解放碑',
    area: '渝中区',
    wasteType: 'paper',
    overflowStatus: OverflowStatus.FULL,
    currentWeight: 97,
    maxCapacity: 100,
    cleanupStaffId: 104,
    cleanupStaffName: '赵六',
    cleanupStaffPhone: '13800138104',
    status: CleanupStatus.PENDING,
    notes: '设备满溢严重，急需清运',
    createdAt: '2024-01-15 17:30:00',
    updatedAt: '2024-01-15 17:30:00'
  }
]

// 模拟清运员数据
const mockCleanupStaff: CleanupStaff[] = [
  { id: 101, name: '张三', phone: '13800138101', area: '朝阳区', status: 'active', currentTasks: 2, maxTasks: 5, createdAt: '2024-01-01' },
  { id: 102, name: '李四', phone: '13800138102', area: '浦东新区', status: 'active', currentTasks: 1, maxTasks: 5, createdAt: '2024-01-01' },
  { id: 103, name: '王五', phone: '13800138103', area: '天河区', status: 'active', currentTasks: 1, maxTasks: 5, createdAt: '2024-01-01' },
  { id: 104, name: '赵六', phone: '13800138104', area: '西湖区', status: 'active', currentTasks: 1, maxTasks: 5, createdAt: '2024-01-01' },
  { id: 105, name: '孙七', phone: '13800138105', area: '武侯区', status: 'active', currentTasks: 0, maxTasks: 5, createdAt: '2024-01-01' }
]

// 模拟清运统计
const mockCleanupStats: CleanupTaskStats = {
  totalTasks: 156,
  pendingTasks: 23,
  inProgressTasks: 8,
  completedTasks: 125,
  fullDevices: 18,
  nearFullDevices: 12,
  averageCompletionTime: 2.5
}

export const useCleanupTasks = () => {
  const loading = ref(false)
  const exporting = ref(false)

  // 搜索表单
  const searchForm = reactive<CleanupTaskQuery>({
    deviceCode: '',
    area: '',
    cleanupStaffName: '',
    cleanupStaffPhone: '',
    wasteType: undefined,
    overflowStatus: undefined,
    status: undefined,
    dateRange: [],
    page: 1,
    size: 10
  })

  // 分页信息
  const pagination = reactive<Pagination>({
    current: 1,
    size: 10,
    total: 0
  })

  // 清运统计
  const cleanupStats = ref<CleanupTaskStats>(mockCleanupStats)

  // 清运任务列表
  const cleanupList = ref<CleanupTask[]>([])

  // 清运员列表
  const cleanupStaffList = ref<CleanupStaff[]>(mockCleanupStaff)

  // 获取满溢状态标签样式
  const getOverflowStatusTag = (status: OverflowStatus) => {
    switch (status) {
      case OverflowStatus.FULL: return 'danger'
      case OverflowStatus.NEAR_FULL: return 'warning'
      case OverflowStatus.NORMAL: return 'success'
      default: return 'info'
    }
  }

  // 获取满溢状态文本
  const getOverflowStatusText = (status: OverflowStatus) => {
    switch (status) {
      case OverflowStatus.FULL: return '满溢'
      case OverflowStatus.NEAR_FULL: return '接近满溢'
      case OverflowStatus.NORMAL: return '正常'
      default: return status
    }
  }

  // 获取任务状态标签样式
  const getTaskStatusTag = (status: CleanupStatus) => {
    switch (status) {
      case CleanupStatus.PENDING: return 'danger'
      case CleanupStatus.COMPLETED: return 'success'
      default: return 'info'
    }
  }

  // 获取任务状态文本
  const getTaskStatusText = (status: CleanupStatus) => {
    switch (status) {
      case CleanupStatus.PENDING: return '待清运'
      case CleanupStatus.COMPLETED: return '已清运'
      default: return status
    }
  }

  // 获取回收类型文本
  const getWasteTypeText = (type: string) => {
    switch (type) {
      case 'paper': return '纸壳类'
      case 'textile': return '织物类'
      case 'mixed': return '混合类'
      default: return type
    }
  }

  // 加载清运任务列表
  const loadCleanupTasks = async () => {
    loading.value = true
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))

      // 模拟数据过滤
      let filteredData = [...mockCleanupTasks]

      if (searchForm.deviceCode) {
        filteredData = filteredData.filter(item =>
          item.deviceCode.includes(searchForm.deviceCode!)
        )
      }

      if (searchForm.area) {
        filteredData = filteredData.filter(item =>
          item.area.includes(searchForm.area!)
        )
      }

      if (searchForm.cleanupStaffName) {
        filteredData = filteredData.filter(item =>
          item.cleanupStaffName.includes(searchForm.cleanupStaffName!)
        )
      }

      if (searchForm.cleanupStaffPhone) {
        filteredData = filteredData.filter(item =>
          item.cleanupStaffPhone.includes(searchForm.cleanupStaffPhone!)
        )
      }

      if (searchForm.wasteType) {
        filteredData = filteredData.filter(item =>
          item.wasteType === searchForm.wasteType
        )
      }

      if (searchForm.overflowStatus) {
        filteredData = filteredData.filter(item =>
          item.overflowStatus === searchForm.overflowStatus
        )
      }

      if (searchForm.status) {
        filteredData = filteredData.filter(item =>
          item.status === searchForm.status
        )
      }

      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        const [startDate, endDate] = searchForm.dateRange
        filteredData = filteredData.filter(item => {
          const createdDate = item.createdAt.split(' ')[0]
          return createdDate >= startDate && createdDate <= endDate
        })
      }

      // 模拟分页
      const startIndex = (pagination.current - 1) * pagination.size
      const endIndex = startIndex + pagination.size
      const pagedData = filteredData.slice(startIndex, endIndex)

      cleanupList.value = pagedData
      pagination.total = filteredData.length

      // 更新统计数据
      cleanupStats.value = {
        totalTasks: mockCleanupTasks.length,
        pendingTasks: mockCleanupTasks.filter(t => t.status === CleanupStatus.Pending).length,
        completedTasks: mockCleanupTasks.filter(t => t.status === CleanupStatus.Completed).length,
        fullDevices: mockCleanupTasks.filter(t => t.overflowStatus === OverflowStatus.FULL).length,
        nearFullDevices: mockCleanupTasks.filter(t => t.overflowStatus === OverflowStatus.NEAR_FULL).length,
        averageCompletionTime: 2.5
      }

    } catch (error) {
      ElMessage.error('获取清运任务列表失败')
      console.error('获取清运任务列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 搜索处理
  const handleSearch = () => {
    pagination.current = 1
    loadCleanupTasks()
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, {
      deviceCode: '',
      area: '',
      cleanupStaffName: '',
      cleanupStaffPhone: '',
      wasteType: undefined,
      overflowStatus: undefined,
      status: undefined,
      dateRange: [],
      page: 1,
      size: 10
    })
    pagination.current = 1
    loadCleanupTasks()
  }

  // 分页改变
  const handlePageChange = (page: number) => {
    pagination.current = page
    loadCleanupTasks()
  }

  // 每页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    loadCleanupTasks()
  }

  // 批量导出
  const handleExport = async () => {
    try {
      exporting.value = true

      // 模拟导出确认
      await ElMessageBox.confirm(
        '确定要导出清运任务数据吗？',
        '导出确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 模拟导出处理
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 构建导出参数
      const exportParams = {
        deviceCode: searchForm.deviceCode,
        area: searchForm.area,
        cleanupStaffName: searchForm.cleanupStaffName,
        cleanupStaffPhone: searchForm.cleanupStaffPhone,
        wasteType: searchForm.wasteType,
        overflowStatus: searchForm.overflowStatus,
        status: searchForm.status,
        startTime: searchForm.dateRange?.[0],
        endTime: searchForm.dateRange?.[1]
      }

      console.log('导出参数:', exportParams)

      // 模拟导出成功
      ElMessage.success('导出任务已提交，文件生成后将自动下载')

      // 模拟文件下载
      setTimeout(() => {
        const blob = new Blob(['清运任务导出数据'], { type: 'application/vnd.ms-excel' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `清运任务_${new Date().toISOString().split('T')[0]}.xlsx`
        a.click()
        URL.revokeObjectURL(url)
      }, 2000)

    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('导出失败')
        console.error('导出失败:', error)
      }
    } finally {
      exporting.value = false
    }
  }

  // 分配任务
  const handleAssignTask = (task: CleanupTask) => {
    ElMessage.info(`分配任务: ${task.taskCode}`)
    // TODO: 实现分配任务逻辑
  }

  // 完成任务
  const handleCompleteTask = (task: CleanupTask) => {
    ElMessageBox.confirm(
      `确定要完成任务 ${task.taskCode} 吗？`,
      '完成任务确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      ElMessage.success('任务已完成')
      // TODO: 实现完成任务逻辑
    }).catch(() => {
      ElMessage.info('已取消')
    })
  }

  // 取消任务
  const handleCancelTask = (task: CleanupTask) => {
    ElMessageBox.confirm(
      `确定要取消任务 ${task.taskCode} 吗？`,
      '取消任务确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      ElMessage.success('任务已取消')
      // TODO: 实现取消任务逻辑
    }).catch(() => {
      ElMessage.info('已取消')
    })
  }

  // 查看详情
  const handleViewDetail = (task: CleanupTask) => {
    ElMessage.info(`查看任务详情: ${task.taskCode}`)
    // TODO: 实现查看详情逻辑
  }

  // 组件挂载时加载数据
  onMounted(() => {
    loadCleanupTasks()
  })

  return {
    loading,
    exporting,
    searchForm,
    pagination,
    cleanupStats,
    cleanupList,
    cleanupStaffList,
    getOverflowStatusTag,
    getOverflowStatusText,
    getTaskStatusTag,
    getTaskStatusText,
    getWasteTypeText,
    loadCleanupTasks,
    handleSearch,
    handleReset,
    handlePageChange,
    handleSizeChange,
    handleExport,
    handleAssignTask,
    handleCompleteTask,
    handleCancelTask,
    handleViewDetail
  }
}
